<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="16">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="搜索项">
              <a-input v-model:value="listQuery.title" placeholder="输入分类名搜索..." />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon>
                  <SyncOutlined />
                </template>
              </a-button>
            </a-tooltip>
            <a-button
              v-permission="{ action: 'email_tpl_cate_add' }"
              type="primary"
              style="margin-left: 12px"
              @click="addNewData"
            >
              <template #icon>
                <PlusOutlined />
              </template>
              新增模板分类
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record._id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #status="{ text: record }">
        <a-tag v-if="record == 1" color="green">启用</a-tag>
        <a-tag v-if="record == -1" color="red">禁用</a-tag>
        <a-tag v-if="record == 0" color="red">禁用</a-tag>
      </template>
      <template #action="{ text: record }">
        <a v-permission="{ action: 'email_tpl_cate_add' }" @click="email_tpl_cate_edit(record)">
          <EditOutlined /> 编辑
        </a>
        <a-divider v-permission="{ action: 'email_tpl_cate_ext' }" type="vertical" />
        <a-dropdown>
          <a v-permission="{ action: 'email_tpl_cate_ext' }" class="ant-dropdown-link">
            更多
            <DownOutlined />
          </a>
          <template #overlay>
            <a-menu>
              <a-menu-item v-permission="{ action: 'email_tpl_cate_del' }" style="color: red">
                <a @click="email_tpl_cate_delete(record)"> <DeleteOutlined /> 删除 </a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-table>
    <a-drawer
      width="65%"
      title="邮件模板分类详情"
      placement="right"
      :open="drawerShow"
      @close="
        () => {
          drawerShow = false
        }
      "
    >
      <template #extra>
        <a-button
          style="margin-right: 8px"
          @click="
            () => {
              drawerShow = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" @click="addServer">提交</a-button>
      </template>
      <a-form
        ref="formRef"
        :model="FormState"
        :rules="FormRule"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-form-item has-feedback required label="上级分类">
          <a-select v-model:value="FormState.pid" placeholder="请选择分类">
            <a-select-option key="0">顶级分类</a-select-option>
            <a-select-option
              v-for="d in allCate"
              :key="d._id"
              :value="d._id"
              :disabled="FormState.cate_id == d._id"
            >
              {{ d.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item has-feedback required label="分类名">
          <a-input v-model:value="FormState.title" placeholder="请输入分类名" />
        </a-form-item>
        <a-form-item label="是否启用" has-feedback required name="status">
          <a-radio-group v-model:value="FormState.status" name="status">
            <a-radio :key="1" :value="1">启用</a-radio>
            <a-radio :key="-1" :value="-1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-drawer>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref } from 'vue'
import {
  Row,
  Col,
  Modal,
  Divider,
  Image,
  Drawer,
  Switch,
  InputPassword,
  InputNumber
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownOutlined
} from '@ant-design/icons-vue'
import { delTplCate, getTplCateList, editTplCateInfo, getAllCateList } from '@/api/email'
import { useRouter } from 'vue-router'
import { requestFailed, requestSuccess } from '@/utils/feedback'

export default defineComponent({
  name: 'AdsList',
  components: {
    SyncOutlined,
    PlusOutlined,
    DownOutlined,
    EditOutlined,
    DeleteOutlined,
    [Row.name]: Row,
    [Drawer.name]: Drawer,
    [Switch.name]: Switch,
    [InputPassword.name]: InputPassword,
    [InputNumber.name]: InputNumber,
    [Col.name]: Col,
    [Image.name]: Image,
    [Divider.name]: Divider
  },
  setup() {
    const formRef = ref()
    const router = useRouter()
    const state = reactive({
      loading: true,
      drawerShow: false,
      dataList: [],
      allCate: [],
      listQuery: {
        pageNo: 1,
        pageSize: 15,
        title: ''
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      pagination: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15,
        current: 1
      },
      columns: [
        {
          title: 'ID',
          dataIndex: '_id'
        },
        {
          title: '分类名',
          dataIndex: 'title'
        },
        {
          title: '状态',
          dataIndex: 'status',
          slots: { customRender: 'status' }
        },
        {
          title: '添加时间',
          dataIndex: 'create_time'
        },
        {
          title: '操作',
          width: '250px',
          slots: { customRender: 'action' }
        }
      ]
    })
    onMounted(() => {
      getDataList()
      getCateDataList()
    })

    function handleTableChange(e) {
      state.loading = true
      state.pagination.pageSize = e.pageSize
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      state.pagination.current = e.current
      getDataList()
    }

    const FormState = reactive<any>({
      _id: '',
      title: '',
      status: ''
    })
    const FormRule = {
      title: [{ required: false, message: '请输入模板分类名', trigger: ['blur', 'change'] }],
      status: [{ required: true, message: '请选择是否启用', trigger: ['blur', 'change'] }]
    }

    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }

    function searchSubmit() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }

    function getDataList() {
      getTplCateList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }
    function getCateDataList() {
      getAllCateList({}).then((res) => {
        state.allCate = res
      })
    }

    function email_tpl_cate_test(itemData) {
      router.push({
        name: 'AdsAnalysis',
        query: { id: itemData._id, title: itemData.title + '（分类：' + itemData.cate + '）' }
      })
    }
    function email_tpl_cate_edit(res) {
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in res) {
        FormState[item] = res[item]
      }
      state.drawerShow = true
    }
    function addNewData() {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerShow = true
    }
    function email_tpl_cate_delete(data) {
      Modal.confirm({
        title: '确认永久删除本模板?',
        content: '【' + data._id + '】',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delTplCate({ id: data._id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              getDataList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    const addServer = () => {
      formRef.value
        .validate()
        .then(() => {
          FormState.is_ssl = FormState.is_ssl_bool == true ? 1 : 0
          editTplCateInfo(FormState).then((res) => {
            if (res.code === 200) {
              requestSuccess(res)
              formRef.value.resetFields()
              state.loading = true
              state.drawerShow = false
              reloadList()
            } else {
              requestFailed(res)
            }
          })
        })
        .catch(() => {
          return false
        })
    }
    return {
      ...toRefs(state),
      handleTableChange,
      reloadList,
      searchSubmit,
      email_tpl_cate_delete,
      formRef,
      addServer,
      FormState,
      FormRule,
      addNewData,
      router,
      email_tpl_cate_edit,
      email_tpl_cate_test,
      getDataList
    }
  }
})
</script>

<style scoped></style>
